package com.hsyg.netty.client;

import com.hsyg.netty.client.handler.ClientHandler3;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 客户端
 */
public class Client3 {
  /**
   * @param host
   * @param port
   * @throws Exception
   */
  public void connect(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap bootstrap = new Bootstrap();
      bootstrap
        .group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel sc) throws Exception {
            ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
            sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
            sc.pipeline().addLast(new StringDecoder());
            sc.pipeline().addLast(new ClientHandler3());
          }
        });

      ChannelFuture future = bootstrap.connect(host, port).sync();

      future.channel().closeFuture().sync();

    } finally {
      group.shutdownGracefully();

    }

  }

  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    int port = 8888;

    if (null != args && args.length > 0) {
      try {
        port = Integer.valueOf(args[0]);

      } catch (Exception e) {
        e.printStackTrace();

      }
    }

    new Client3().connect("localhost", port);

  }
}
